package com.fw.service.url.impl;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Value;

import com.fw.service.url.URLService;

public class URLServiceImpl implements URLService {

    // #('${settings.some.property}')
    @Value("${config.urls}")
    private String urls;

    private static Logger log = Logger.getLogger(URLServiceImpl.class);

    @Override
    public List<String> getLinks(String url) {
	List<String> hrefList = new ArrayList<String>();
	try {
	    log.debug("getLinks url = " + url);
	    Document doc = Jsoup.connect(url).get();
	    Elements links = doc.select("a[href]");
	    // href ...
	    for (Element link : links) {
		String href = link.attr("abs:href");
		if (href != null && !href.isEmpty() && !hrefList.contains(href)) {
		    log.debug("href = " + href);
		    hrefList.add(href);
		}
	    }
	} catch (IOException e) {
	    log.error(e, e.getCause());
	}
	return hrefList;
    }

    @Override
    public Boolean checkLink(String link) {
	Boolean success = Boolean.FALSE;
	try {

	    URL linkUrl = new URL(link);
	    HttpURLConnection httpURLConnection = (HttpURLConnection) linkUrl.openConnection();
	    httpURLConnection.setRequestMethod("HEAD");
	    int responseCode = httpURLConnection.getResponseCode();
	    if (responseCode == 200) {
		success = Boolean.TRUE;
	    }
	} catch (IOException e) {
	    log.error(e, e.getCause());
	}
	log.debug("checkLink link = " + link + ", success = " + success);
	return success;
    }

    @Override
    public Boolean process() {
	Boolean success = Boolean.FALSE;
	try {
	    log.debug("begin process " + urls + ", " + new Date());
	    String[] urlArray = urls.split("\\|");
	    for (String url : urlArray) {
		List<String> links = this.getLinks(url);
		for (String link : links) {
		    this.checkLink(link);
		}
	    }
	    success = Boolean.TRUE;
	} catch (Exception e) {
	    log.error(e, e.getCause());
	}
	return success;
    }

}
